package ph.com.gs3.formalistics.model.facades;

import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.LocalDataAccessObject.InsertFailedException;
import ph.com.gs3.formalistics.model.ldao.CompaniesLDAO;
import ph.com.gs3.formalistics.model.vo.business.Company;
import android.content.Context;

public class CompaniesDataWriter {

	public static final String TAG = CompaniesDataWriter.class.getSimpleName();

	private CompaniesLDAO companiesLDAO;

	public CompaniesDataWriter(Context context) {
		companiesLDAO = new CompaniesLDAO(context);
	}

	public Company registerCompany(Company company) {

		Company registeredCompany;

		companiesLDAO.open();
		Company existingCompany = companiesLDAO.getCompany(company.getWebId(), company.getServer());

		if (existingCompany == null) {
			try {
				FLLogger.d(TAG, "Registering new company " + company.toString());
				registeredCompany = companiesLDAO.saveCompany(company);
			} catch (InsertFailedException e) {
				// Unrecoverable error
				throw new RuntimeException(e);
			}
		} else {
			registeredCompany = existingCompany;
		}
		companiesLDAO.close();

		return registeredCompany;

	}

}
